import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { Observable, of, combineLatest } from 'rxjs'
import { concatMap, map, switchMap } from 'rxjs/operators'
import { NzModalService } from 'ng-zorro-antd'
import { DataService } from '@shared/services/data.service'
import { PageService } from '@shared/services/page.service'
import { StoreService } from '../../store.service'
import { ETabScrollStatus, EPaymentBrand } from '@shared/enums'
import { StoreFull } from '@shared/interfaces/store'
import { IChannelOption } from './tab-ec-channels.interface'
import { TabECChannelsService } from './tab-ec-channels.service'
import { I18NService } from '@core'
import { getChannelLogoURL } from 'app/utils/helpers'
import { StoreDataService } from '../../store-data.service'

@Component({
  selector: 'app-store-detail-tab-ec-channels',
  templateUrl: './tab-ec-channels.component.html',
})
export class StoreDetailTabECChannelsComponent implements OnInit {
  channelOptions$: Observable<IChannelOption[]>
  loading = false
  storeFull: StoreFull

  constructor(
    private pageService: PageService,
    private router: Router,
    private route: ActivatedRoute,
    private modelService: NzModalService,
    private dataService: DataService,
    private storeService: StoreService,
    private storeDataService: StoreDataService,
    private tabECChannelsService: TabECChannelsService,
    private i18n: I18NService,
  ) {}

  ngOnInit(): void {
    // fetch available channels of current store
    const channels$ = this.dataService.storeFull$.value$.pipe(
      concatMap(full => {
        this.storeFull = full
        if (full.store && full.store.common && full.store.common.insCode) {
          return of(full.store.common.insCode)
        }

        return this.route.params.pipe(
          concatMap(params => this.storeService.getOne(params.id)),
          map(storeFull => storeFull.store.common.insCode),
        )
      }),
      switchMap(insCode => this.storeService.getAcquirerECChannels(insCode)),
    )

    this.channelOptions$ = combineLatest(this.dataService.storeFull$.value$, channels$).pipe(
      map(([storeFull, ecPayChannels]) => {
        const m: Map<string, IChannelOption> = new Map();

        (storeFull.ecPayChannels || []).forEach(chan => {
          m.set(chan.paymentBrand, {
            paymentBrand: chan.chanCode,
            data: chan,
            imgUrl: getChannelLogoURL(chan.chanCode),
            channelColumns: this.tabECChannelsService.getChannelColumns(chan),
            checked: true,
          })
        })

        for (const chan of ecPayChannels) {
          if (m.has(chan.chanCode)) {
            continue
          }

          m.set(chan.chanCode, {
            paymentBrand: chan.chanCode,
            imgUrl: getChannelLogoURL(chan.chanCode),
            channelColumns: [],
            checked: false,
          })
        }

        return Array.from(m.values())
      }),
    )

    this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
  }

  goToCreate(brand: EPaymentBrand) {
    this.storeDataService.setStore(this.storeFull.store)
    this.router.navigate(['../../ec/channel'], {
      relativeTo: this.route,
      queryParams: {
        paymentBrand: brand,
      },
    })
  }

  onRouteEditClick(option: IChannelOption) {
    this.storeDataService.setStore(this.storeFull.store)
    const chan = option.data
    this.dataService.setStoreRoute(chan)
    this.router.navigate(['../../ec/channel', chan.id], { relativeTo: this.route })
  }

  onRouteSwitchClick(option: IChannelOption): void {
    if (option.loading) {
      return
    }

    if (!option.checked) {
      this.goToCreate(option.paymentBrand)
      return
    }

    this.modelService.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('BIZ.ACQUIRER.OTHER.QR_CHANNEL.DELETE_CHANNEL_CONFIRM'),
      nzOnOk: () => this.closeChannel(option),
    })
  }

  closeChannel(option: IChannelOption) {
    option.loading = true
    this.storeService.deleteQRRoute(this.storeFull.store.common.intStoreCode, option.data.id).subscribe(() => {
      option.loading = false
      option.checked = !option.checked
      const channelsRemain = this.storeFull.ecPayChannels.filter(item => item.id !== option.data.id)
      this.storeFull.ecPayChannels = channelsRemain
      this.dataService.setStoreFull(this.storeFull)
    })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
